<template>
  <XenPageLayout
    title="编辑应聘申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 标签按钮网格 -->
      <view class="tab-grid">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          class="tab-button"
          :class="{ active: currentTab === index }"
          @click="switchTab(index)"
          @touchstart="() => {}"
        >
          <text class="tab-label">{{ tab.title }}</text>
        </view>
      </view>

      <!-- 标签内容区域 -->
      <view class="tab-content-wrapper">
        <!-- 基本信息 -->
        <view v-show="currentTab === 0" class="tab-content">
          <XenDynamicFormCard
            title="编辑应聘申请信息"
            :subtitle="`申请单ID: ${interviewId || 'I12345'}`"
            :sections="formSections"
            :modelValue="formData"
            :errors="formErrors"
            :showFooter="false"
            :idCardExpiryDisplayState="idCardExpiryDisplayState"
            @update:modelValue="handleFormDataChange"
            @fieldBlur="handleFieldBlur"
            @pickerChange="handlePickerChange"
            @datetimeChange="handleDateTimeChange"
            @imageUpload="handleImageUpload"
            @imageSuccess="handleImageSuccess"
            @imageFail="handleImageFail"
            @imageDelete="handleImageDelete"
            @fileUpload="handleFileUpload"
            @fileSuccess="handleFileSuccess"
            @fileFail="handleFileFail"
            @fileDelete="handleFileDelete"
            @departmentPickerChange="handleDepartmentPickerChange"
            @departmentPickerOpen="handleDepartmentPickerOpen"
            @departmentPickerClose="handleDepartmentPickerClose"
            @autoCompleteChange="handleAutoCompleteChange"
            @autoCompleteSearch="handleAutoCompleteSearch"
          />
        </view>

        <!-- 学习经历 -->
        <view v-show="currentTab === 1" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">学习经历信息</text>
              <text class="card-subtitle">学校、专业、学历等教育背景信息</text>
            </view>
            <view class="card-content">
              <InterviewEducationInfo
                ref="educationRef"
                :person-id="interviewId"
                @add="handleAddEducation"
                @edit="handleEditEducation"
              />
            </view>
          </view>
        </view>

        <!-- 家庭成员 -->
        <view v-show="currentTab === 2" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">家庭成员信息</text>
              <text class="card-subtitle"
                >家属姓名、关系等家庭成员详细信息</text
              >
            </view>
            <view class="card-content">
              <InterviewFamilyInfo
                ref="familyRef"
                :person-id="interviewId"
                @add="handleAddFamily"
                @edit="handleEditFamily"
              />
            </view>
          </view>
        </view>

        <!-- 工作经历 -->
        <view v-show="currentTab === 3" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">工作经历信息</text>
              <text class="card-subtitle"
                >以往工作单位、岗位、时间等工作经历</text
              >
            </view>
            <view class="card-content">
              <InterviewWorkInfo
                ref="workRef"
                :person-id="interviewId"
                @add="handleAddWork"
                @edit="handleEditWork"
              />
            </view>
          </view>
        </view>

        <!-- 荣誉职称 -->
        <view v-show="currentTab === 4" class="tab-content">
          <view class="subtable-card">
            <view class="card-header">
              <text class="card-title">荣誉职称信息</text>
              <text class="card-subtitle"
                >资质证书、职称等级、荣誉奖项信息</text
              >
            </view>
            <view class="card-content">
              <InterviewHonorInfo
                ref="honorRef"
                :person-id="interviewId"
                @add="handleAddHonor"
                @edit="handleEditHonor"
              />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 弹框已移到popup插槽 -->

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />

    <!-- 弹出层插槽：专门用于渲染各种弹框组件 -->
    <template #popup>
      <!-- 学习经历弹框 -->
      <InterviewUnifiedAddPopupFixed
        v-model:show="showEducationPopup"
        :config="educationPopupConfig"
        :person-id="interviewId"
        :edit-data="editingEducation"
        :on-submit="handleEducationSubmit"
        @confirm="handleEducationSuccess"
      />

      <!-- 家庭成员弹框 -->
      <InterviewUnifiedAddPopupFixed
        v-model:show="showFamilyPopup"
        :config="familyPopupConfig"
        :person-id="interviewId"
        :edit-data="editingFamily"
        :on-submit="handleFamilySubmit"
        @confirm="handleFamilySuccess"
      />

      <!-- 工作经历弹框 -->
      <InterviewUnifiedAddPopupFixed
        v-model:show="showWorkPopup"
        :config="workPopupConfig"
        :person-id="interviewId"
        :edit-data="editingWork"
        :on-submit="handleWorkSubmit"
        @confirm="handleWorkSuccess"
      />

      <!-- 荣誉职称弹框 -->
      <InterviewUnifiedAddPopupFixed
        v-model:show="showHonorPopup"
        :config="honorPopupConfig"
        :person-id="interviewId"
        :edit-data="editingHonor"
        :on-submit="handleHonorSubmit"
        @confirm="handleHonorSuccess"
      />
    </template>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import {
  getFormSectionsByPageType,
  getFilteredFormSections,
} from "./form-config";
import { useInterviewInfo } from "./composables/useInfo";
// 导入统一事件系统
import { InterviewInfoEvents } from "@/utils/eventBus";
// 导入API和接口类型
import SysHrInterviewRequestBillApi from "./api/index";
import type { ISysHrInterviewRequestBillVm } from "./api/interface";
// 导入文件上传函数
import { uploadImage } from "@/utils/unirequest";
// 导入子表组件
import InterviewEducationInfo from "./components/InterviewEducationInfo.vue";
import InterviewFamilyInfo from "./components/InterviewFamilyInfo.vue";
import InterviewWorkInfo from "./components/InterviewWorkInfo.vue";
import InterviewHonorInfo from "./components/InterviewHonorInfo.vue";
// 导入弹框组件和配置
import InterviewUnifiedAddPopupFixed from "./components/InterviewUnifiedAddPopupFixed.vue";
import {
  educationConfig,
  familyConfig,
  workConfig,
  honorConfig,
} from "./components/popupConfigs";

// 获取路由参数
const interviewId = ref<string>("");

// 创建API实例
const api = SysHrInterviewRequestBillApi();

// 审核权限标识
const isMyApprove = ref<boolean>(false);

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 弹框状态管理
const showEducationPopup = ref<boolean>(false);
const showFamilyPopup = ref<boolean>(false);
const showWorkPopup = ref<boolean>(false);
const showHonorPopup = ref<boolean>(false);

// 编辑状态管理
const editingEducation = ref<any>(null);
const editingFamily = ref<any>(null);
const editingWork = ref<any>(null);
const editingHonor = ref<any>(null);

// 弹框配置
const educationPopupConfig = ref(educationConfig);
const familyPopupConfig = ref(familyConfig);
const workPopupConfig = ref(workConfig);
const honorPopupConfig = ref(honorConfig);

// 当前标签页
const currentTab = ref(0);

// 标签页配置
const tabs = ref([
  {
    title: "基本信息",
  },
  {
    title: "学习经历",
  },
  {
    title: "家庭成员",
  },
  {
    title: "工作经历",
  },
  {
    title: "荣誉职称",
  },
]);

// 切换标签页
const switchTab = (index: number) => {
  currentTab.value = index;
};

// 获取编辑页面的表单分组
const baseFormSections = getFormSectionsByPageType("edit");

// 动态过滤表单字段（支持条件显示）
const formSections = computed(() => {
  return getFilteredFormSections(baseFormSections, formData);
});

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "save",
    label: isMyApprove.value ? "取消" : "保存",
    type: "success" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用应聘申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  loadInterviewDetail,
  search,
  originalData,
  convertFormDataToApiFormatForEdit,
  recognizeIdentityCard,
  idCardExpiryDisplayState,
} = useInterviewInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);

  // 特殊处理退伍军人字段
  if (newData.hasOwnProperty("isVeteran")) {
    const isVeteranValue = newData.isVeteran;
    // 如果选择否，清空退伍证图片
    if (isVeteranValue === "否" || !isVeteranValue) {
      formData.veteranCertificateId = null;
    }
  }

  // 特殊处理亲属关系字段
  if (newData.hasOwnProperty("hasRelativeInCompany")) {
    const hasRelativeValue = newData.hasRelativeInCompany;
    // 如果选择否，清空亲属姓名和亲属关系
    if (hasRelativeValue === "否" || !hasRelativeValue) {
      formData.relativeName = "";
      formData.relationshipType = "";
    }
  }
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  console.log("自动补全变化处理:", fieldKey, _value, option);

  // 注意：不要在这里设置formData[fieldKey]，因为XenAutoComplete组件已经通过update:modelValue事件设置了
  // XenAutoComplete会：
  // 1. 显示option.text在输入框中
  // 2. emit update:modelValue(option.value) 设置formData[fieldKey] = option.value
  // 3. emit change事件到这里处理额外的逻辑

  if (option) {
    // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;
    console.log(`设置 formData[${fieldKey}] = ${option.text}`);
    console.log(`设置 pickerValues[${fieldKey}] = ${option.value}`);

    // 如果是招聘发布单选择，确保显示Title在输入框中
    if (fieldKey === "recruitPublishRequestBillId") {
      console.log("招聘发布单选择处理:", {
        text: option.text,
        value: option.value,
        subtitle: option.subtitle,
        extData: option.extData,
      });

      // 确保输入框显示的是Title（岗位标题）
      console.log(
        `招聘发布单输入框将显示: ${option.text} (来自Title: ${option.extData?.title})`,
      );

      // 验证option.text确实是Title
      if (option.extData?.title && option.text !== option.extData.title) {
        console.warn("警告：option.text 与 option.extData.title 不一致！");
        console.log("option.text:", option.text);
        console.log("option.extData.title:", option.extData.title);
      }

      if (option.subtitle) {
        // 从subtitle中提取单据编号，格式为 "单据编号: 12345 | 部门名称"
        const billCodeMatch = option.subtitle.match(/单据编号:\s*(\S+)/);
        if (billCodeMatch) {
          console.log("选择的招聘发布单编号:", billCodeMatch[1]);
        }
      }

      // 可以从扩展数据中获取更多信息
      if (option.extData) {
        console.log("招聘发布单详细信息:", option.extData);
        // 这里可以根据需要自动填入一些字段，比如岗位信息等
        // 例如：如果招聘发布单有关联的部门信息，可以自动设置
      }
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";
    console.log(`清空 formData[${fieldKey}] 和 pickerValues[${fieldKey}]`);

    // 如果清空招聘发布单选择，也清空相关字段
    if (fieldKey === "recruitPublishRequestBillId") {
      // 根据需要清空相关字段
      console.log("清空招聘发布单选择");
    }
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
  console.log("搜索:", fieldKey, query);
};

// 获取路由参数
onLoad((options) => {
  if (options?.id) {
    interviewId.value = options.id;
  } else {
    uni.showToast({
      title: "缺少ID参数",
      icon: "none",
    });
  }
});

// 页面加载时获取数据
onMounted(async () => {
  // 初始化选项数据
  await initializeOptions();

  // 加载应聘申请详情
  if (interviewId.value) {
    const result = await loadInterviewDetail(interviewId.value);
    if (!result.success) {
      uni.showToast({
        title: "加载数据失败",
        icon: "none",
      });
    } else {
      // 保存审核权限标识
      isMyApprove.value = result.isMyApprove || false;
    }
  }
});

// 图片上传处理 (@select事件)
const handleImageUpload = async (field: any, event: any) => {
  // 图片上传逻辑
  console.log("图片上传:", field.key, event);

  const file = event.tempFiles?.[0] || event.tempFiles;
  const filePath = file?.path || file?.tempFilePath;

  if (filePath) {
    // 检查文件大小
    const maxSize = field.fileConfig?.maxSize || 5; // 默认5MB
    const fileSizeMB = file.size / (1024 * 1024);

    if (fileSizeMB > maxSize) {
      uni.showToast({
        title: `文件大小不能超过${maxSize}MB`,
        icon: "none",
        duration: 3000,
      });
      return;
    }

    // 如果是个人照片，特殊处理：阻止组件自动预览，等AI处理完成后再显示
    if (field.key === "photoId") {
      // 立即清空字段，阻止组件显示预览
      const newData = { ...formData, [field.key]: null };
      Object.assign(formData, newData);

      try {
        // 调用文件上传API获取fileId
        const fileId = await uploadImage(filePath);
        console.log(`${field.label}上传成功，文件ID:`, fileId);

        console.log("开始人像验证，图片ID:", fileId);
        const validateResult = await api.validatePortrait({ ImageId: fileId });
        console.log("人像验证结果:", validateResult);

        if (validateResult.Code !== 200) {
          // 验证失败，显示错误信息
          uni.showToast({
            title: validateResult.Message,
            icon: "none",
            duration: 3000,
          });
          // 不更新表单数据，保持字段为空
          return;
        } else {
          // 验证通过，显示成功提示
          uni.showToast({
            title: validateResult.Message,
            icon: "success",
            duration: 1500,
          });

          // 只使用处理后的图片ID
          if (validateResult.Data) {
            const processedImageId = validateResult.Data;
            console.log("使用处理后的图片ID:", processedImageId);
            // 更新表单数据为处理后的图片ID
            const finalData = { ...formData, [field.key]: processedImageId };
            Object.assign(formData, finalData);
          }
          return;
        }
      } catch (error) {
        console.error("人像验证失败:", error);
        uni.showToast({
          title: "照片验证失败，请重试",
          icon: "none",
          duration: 3000,
        });
        // 验证失败，不更新表单数据，保持空白
        return;
      }
    }

    // 其他字段的正常处理流程
    // 调用文件上传API获取fileId
    const fileId = await uploadImage(filePath);
    console.log(`${field.label}上传成功，文件ID:`, fileId);

    // 更新表单数据 - 使用响应式方式
    const newData = { ...formData, [field.key]: fileId };
    Object.assign(formData, newData);

    // 如果是身份证照片，触发OCR识别
    if (
      field.key === "idCardFrontPhotoId" ||
      field.key === "idCardBackPhotoId"
    ) {
      const cardType = field.key === "idCardFrontPhotoId" ? "front" : "back";
      await recognizeIdentityCard(fileId, cardType);
    }
  }
};

const handleImageSuccess = async (field: any, event: any) => {
  // 图片上传成功处理
  console.log("图片上传成功:", field.key, event);

  // 如果是个人照片（portrait-camera类型），进行人像验证
  if (field.key === "photoId" && field.type === "portrait-camera") {
    // 立即清空字段，阻止显示原始图片
    const clearData = { ...formData, [field.key]: null };
    Object.assign(formData, clearData);

    const fileId = event.fileId;
    if (fileId) {
      try {
        // 显示loading状态
        uni.showLoading({
          title: "正在生成证件照...",
          mask: true,
        });

        console.log("开始人像验证，图片ID:", fileId);
        const validateResult = await api.validatePortrait({ ImageId: fileId });
        console.log("人像验证结果:", validateResult);

        // 隐藏loading
        uni.hideLoading();

        if (validateResult.Code !== 200) {
          // 验证失败，显示错误信息
          uni.showToast({
            title: validateResult.Message,
            icon: "none",
            duration: 3000,
          });
          // 保持字段为空
          return;
        } else {
          // 验证通过，显示成功提示
          uni.showToast({
            title: validateResult.Message,
            icon: "success",
            duration: 1500,
          });

          // 只使用处理后的图片ID
          if (validateResult.Data) {
            const processedImageId = validateResult.Data;
            console.log("使用处理后的图片ID:", processedImageId);
            // 更新表单数据为处理后的图片ID
            const finalData = { ...formData, [field.key]: processedImageId };
            Object.assign(formData, finalData);
          }
        }
      } catch (error) {
        // 隐藏loading
        uni.hideLoading();

        console.error("人像验证失败:", error);
        uni.showToast({
          title: "照片验证失败，请重试",
          icon: "none",
          duration: 3000,
        });
        // 验证失败，保持字段为空
        return;
      }
    }
  }

  // 身份证识别已在 handleImageUpload 中处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 图片删除逻辑
  console.log("图片删除:", field.key, event);

  // 清空表单数据中对应的字段
  const newData = { ...formData, [field.key]: null };
  Object.assign(formData, newData);

  // 如果删除的是身份证照片，清空相关的识别字段
  if (field.key === "idCardFrontPhotoId") {
    Object.assign(formData, {
      name: "",
      gender: "",
      birthDate: "",
      ethnicity: "",
      idCardNo: "",
      householdRegistration: "",
      nativePlace: "",
    });
  } else if (field.key === "idCardBackPhotoId") {
    Object.assign(formData, {
      idCardExpiryDate: "",
    });
    // 重置身份证有效期显示状态
    idCardExpiryDisplayState.value = "normal";
  }
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 通用的审核处理方法
const performAudit = async (actionName: string) => {
  const loadingTitle = actionName === "同意" ? "提交中..." : "取消中...";
  uni.showLoading({ title: loadingTitle });

  // 确保有原始数据（包含BillStatus和WorkflowStatus）
  if (!originalData.value) {
    uni.hideLoading();
    uni.showToast({
      title: "缺少原始数据，请重新加载页面",
      icon: "none",
    });
    return;
  }

  // 构造approve接口请求参数
  // 1. 先使用用户编辑的表单数据构造基础Entity
  const editData = convertFormDataToApiFormatForEdit();

  // 2. 然后覆盖状态字段，使用原始数据中的状态信息
  editData.Entity.BillStatus = originalData.value.BillStatus;
  editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;

  const requestData: ISysHrInterviewRequestBillVm = {
    ActionName: actionName,
    Entity: editData.Entity, // 使用用户编辑的数据 + 原始状态字段
    IsMyApprove: isMyApprove.value, // 使用从详情接口获取的审核权限标识
    Remark: null, // 不需要备注弹框
  };

  // 调用approve接口
  const result = await api.approve(requestData);

  uni.hideLoading();

  if (result) {
    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      InterviewInfoEvents.emit("refresh", {
        id: result.ID || "",
        data: searchResponse,
        customAction: actionName === "同意" ? "approve" : "reject",
      });
    } else {
      // 如果获取失败，仍然发送简单的刷新事件作为备用方案
      InterviewInfoEvents.emit("refresh", {
        id: result.ID || "",
        customAction: actionName === "同意" ? "approve" : "reject",
      });
    }

    const successTitle = actionName === "同意" ? "提交成功" : "取消成功";
    uni.showToast({
      title: successTitle,
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    const errorTitle =
      actionName === "同意" ? "提交失败，请重试" : "取消失败，请重试";
    uni.showToast({
      title: errorTitle,
      icon: "none",
    });
  }
};

// 编辑保存方法
const performEdit = async (isSubmit: boolean = false) => {
  const loadingTitle = isSubmit ? "提交中..." : "保存中...";
  uni.showLoading({ title: loadingTitle });

  // 确保有原始数据
  if (!originalData.value) {
    uni.hideLoading();
    uni.showToast({
      title: "缺少原始数据，请重新加载页面",
      icon: "none",
    });
    return;
  }

  // 构造Edit接口请求参数
  const editData = convertFormDataToApiFormatForEdit();

  // 确保使用原始数据中的状态字段
  editData.Entity.BillStatus = originalData.value.BillStatus;
  editData.IsMyApprove = isMyApprove.value; // 使用从详情接口获取的IsMyApprove值

  // 根据操作类型设置WorkflowStatus
  if (isSubmit) {
    // 提交操作：设置WorkflowStatus为"提交中"
    editData.Entity.WorkflowStatus = "提交中";
  } else {
    // 保存操作：使用原始的WorkflowStatus
    editData.Entity.WorkflowStatus = originalData.value.WorkflowStatus;
  }

  // 调用Edit接口
  const result = await api.edit(editData);

  uni.hideLoading();

  if (result) {
    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      InterviewInfoEvents.emit("refresh", {
        id: result.ID || "",
        data: searchResponse,
        customAction: isSubmit ? "submit" : "save",
      });
    } else {
      // 如果获取失败，仍然发送简单的刷新事件作为备用方案
      InterviewInfoEvents.emit("refresh", {
        id: result.ID || "",
        customAction: isSubmit ? "submit" : "save",
      });
    }

    const successTitle = isSubmit ? "提交成功" : "保存成功";
    uni.showToast({
      title: successTitle,
      icon: "success",
      success: () => {
        if (isSubmit) {
          // 提交成功后跳转页面
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        } else {
          // 保存成功后回到页面顶部
          setTimeout(() => {
            scrollToTop();
          }, 300);
        }
      },
    });
  } else {
    const errorTitle = isSubmit ? "提交失败，请重试" : "保存失败，请重试";
    uni.showToast({
      title: errorTitle,
      icon: "none",
    });
  }
};

// 同意操作
const handleApprove = async () => {
  await performAudit("同意");
};

// 拒绝操作
const handleReject = async () => {
  await performAudit("拒绝");
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "save":
      handleSaveAction();
      break;
    case "submit":
      handleSubmitAction();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 保存按钮处理方法
const handleSaveAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用拒绝接口
    await handleReject();
  } else {
    // 如果IsMyApprove为false，调用编辑保存接口
    await performEdit(false);
  }
};

// 提交按钮处理方法
const handleSubmitAction = async () => {
  if (isMyApprove.value) {
    // 如果IsMyApprove为true，调用同意接口
    await handleApprove();
  } else {
    // 如果IsMyApprove为false，调用编辑提交接口（WorkflowStatus设为"提交中"）
    await performEdit(true);
  }
};

// 新增和编辑事件处理方法
const handleAddEducation = () => {
  editingEducation.value = null;
  showEducationPopup.value = true;
};

const handleEditEducation = (item: any) => {
  editingEducation.value = item;
  showEducationPopup.value = true;
};

const handleAddFamily = () => {
  editingFamily.value = null;
  showFamilyPopup.value = true;
};

const handleEditFamily = (item: any) => {
  editingFamily.value = item;
  showFamilyPopup.value = true;
};

const handleAddWork = () => {
  editingWork.value = null;
  showWorkPopup.value = true;
};

const handleEditWork = (item: any) => {
  editingWork.value = item;
  showWorkPopup.value = true;
};

const handleAddHonor = async () => {
  editingHonor.value = null;
  await loadHonorPopupConfig(); // 加载资质类别数据
  showHonorPopup.value = true;
};

const handleEditHonor = async (item: any) => {
  editingHonor.value = item;
  await loadHonorPopupConfig(); // 加载资质类别数据
  showHonorPopup.value = true;
};

// 加载荣誉职称弹框配置（资质类别数据）
const loadHonorPopupConfig = async () => {
  try {
    console.log("开始加载资质类别数据...");
    const res = await api.getProfessionalTitleTypes();
    console.log("资质类别API返回数据:", res);

    if (res && Array.isArray(res)) {
      // 找到资质类别字段并更新选项
      const section = honorPopupConfig.value.sections.find(
        (s: any) => s.key === "honor_info",
      );
      if (section) {
        const row = section.rows.find((r: any) => r.key === "row1");
        if (row) {
          const field = row.fields.find(
            (f: any) => f.key === "ProfessionalTitleTypeId",
          );
          if (field) {
            const options = res.map((item) => {
              console.log("处理资质类别项:", item);
              return {
                value: item.Value,
                text: item.Text,
              };
            });
            console.log("转换后的选项数据:", options);
            field.options = options;
          }
        }
      }
    }
  } catch (error) {
    console.error("加载资质类别失败:", error);
    uni.showToast({
      title: "加载资质类别失败",
      icon: "none",
    });
  }
};

// 弹框提交处理方法
const handleEducationSubmit = async (formData: any) => {
  // 如果是编辑模式，先删除原记录
  if (editingEducation.value && editingEducation.value.ID) {
    await api.deleteEducation([editingEducation.value.ID]);
  }

  // 处理文件ID字符串，转换为对象数组格式
  let fileObjects: { FileId: string }[] = [];
  if (formData.SelectedEducationFilesIds) {
    const fileIds = formData.SelectedEducationFilesIds.split(",").filter(
      (id: string) => id.trim(),
    );
    fileObjects = fileIds.map((id: string) => ({ FileId: id }));
  }

  // 从formData中排除SelectedEducationFilesIds，因为它现在在VM层级
  const { SelectedEducationFilesIds, ...entityData } = formData;

  const submitData = {
    Entity: {
      ...entityData,
      PersonId: interviewId.value,
    },
    SelectedEducationFilesIds: fileObjects,
  };

  await api.addEducation(submitData);
};

const handleFamilySubmit = async (formData: any) => {
  // 如果是编辑模式，先删除原记录
  if (editingFamily.value && editingFamily.value.ID) {
    await api.deleteFamily([editingFamily.value.ID]);
  }

  const requestData = {
    Entity: {
      ...formData,
      PersonId: interviewId.value,
    },
  };
  await api.addFamily(requestData);
};

const handleWorkSubmit = async (formData: any) => {
  // 如果是编辑模式，先删除原记录
  if (editingWork.value && editingWork.value.ID) {
    await api.deleteWork([editingWork.value.ID]);
  }

  const requestData = {
    Entity: {
      ...formData,
      PersonId: interviewId.value,
    },
  };
  await api.addWork(requestData);
};

const handleHonorSubmit = async (formData: any) => {
  // 如果是编辑模式，先删除原记录
  if (editingHonor.value && editingHonor.value.ID) {
    await api.deleteHonor([editingHonor.value.ID]);
  }

  const requestData = {
    Entity: {
      ...formData,
      PersonId: interviewId.value,
    },
  };
  await api.addHonor(requestData);
};

// 弹框成功回调方法
const handleEducationSuccess = () => {
  // 刷新学习经历列表
  getEducationRef()?.loadEducationList?.();
};

const handleFamilySuccess = () => {
  // 刷新家庭成员列表
  getFamilyRef()?.loadFamilyList?.();
};

const handleWorkSuccess = () => {
  // 刷新工作经历列表
  getWorkRef()?.loadWorkList?.();
};

const handleHonorSuccess = () => {
  // 刷新荣誉职称列表
  getHonorRef()?.loadHonorList?.();
};

// 获取子组件引用（需要在子组件上添加ref）
const educationRef = ref();
const familyRef = ref();
const workRef = ref();
const honorRef = ref();

const getEducationRef = () => educationRef.value;
const getFamilyRef = () => familyRef.value;
const getWorkRef = () => workRef.value;
const getHonorRef = () => honorRef.value;

// 返回顶部功能
const scrollToTop = () => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 200,
  });
};
</script>

<style lang="scss" scoped>
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: calc(100vh - 80px);
}

/* 标签按钮网格布局 */
.tab-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16rpx;
  padding: 32rpx 24rpx;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 0 0 32rpx 32rpx;
  margin-bottom: 24rpx;
}

.tab-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 16rpx 12rpx;
  border-radius: 20rpx;
  background: rgba(255, 255, 255, 0.15);
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(8px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;

  &:active {
    transform: scale(0.95);
  }

  &.active {
    background: rgba(255, 255, 255, 0.95);
    border-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
    transform: translateY(-4rpx);

    .tab-label {
      color: #1f2937;
      font-weight: 600;
    }
  }

  .tab-label {
    font-size: 24rpx;
    color: #ffffff;
    text-align: center;
    font-weight: 500;
    line-height: 1.2;
    transition: all 0.3s ease;
  }
}

/* 标签内容区域 */
.tab-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tab-content {
  flex: 1;
  padding: 0 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .tab-grid {
    gap: 12rpx;
    padding: 24rpx 16rpx;
  }

  .tab-button {
    padding: 16rpx 8rpx;

    .tab-label {
      font-size: 22rpx;
    }
  }

  .tab-content {
    padding: 0 12px;
  }
}

/* 超小屏幕优化 */
@media (max-width: 600rpx) {
  .tab-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 8rpx;
  }

  .tab-button {
    padding: 12rpx 6rpx;

    .tab-label {
      font-size: 20rpx;
    }
  }
}

/* 子表卡片样式，与XenDynamicFormCard保持一致 */
.subtable-card {
  background: #ffffff;
  border-radius: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  overflow: hidden;
  margin-bottom: 24rpx;
  /* 设置为flex容器，占满父容器 */
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 400rpx;
}

.card-header {
  background: #ffffff;
  padding: 40rpx 48rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.card-title {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 8rpx;
}

.card-subtitle {
  display: block;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  font-weight: 400;
}

.card-content {
  flex: 1;
  padding: 48rpx;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .subtable-card {
    margin-bottom: 20rpx;
    border-radius: 28rpx;
    min-height: 350rpx;
  }

  .card-header {
    padding: 36rpx 40rpx;
  }

  .card-title {
    font-size: 32rpx;
    margin-bottom: 6rpx;
  }

  .card-subtitle {
    font-size: 26rpx;
  }

  .card-content {
    padding: 40rpx;
  }
}

@media (max-width: 600rpx) {
  .subtable-card {
    min-height: 300rpx;
  }

  .card-header {
    padding: 32rpx 36rpx;
  }

  .card-title {
    font-size: 30rpx;
    margin-bottom: 4rpx;
  }

  .card-subtitle {
    font-size: 24rpx;
  }

  .card-content {
    padding: 36rpx;
  }
}
</style>
